package com.daiyang.lottery.common.util;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    public JacksonUtil() {

    }
    /**
     * 静态代码块单例
     */
    private final static ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);
    }
    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        }
        catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }
    /**
     * 反序列化
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String json, Class<T> valueType) {
        return tryParse(()->JacksonUtil.getObjectMapper().readValue(json, valueType));
    }

    /**
     * 反序列化List
     * @param json
     * @param valueType
     * @return
     * @param <T>
     */

    public static <T> T readListValue(String json, Class<?> valueType) {
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
                .constructCollectionType(List.class, valueType);
        return tryParse(()->JacksonUtil.getObjectMapper().readValue(json, javaType));

    }

    /**
     * 序列1
     */
    public static String writeValueAsString(Object value) {
        return tryParse(()->JacksonUtil.getObjectMapper().writeValueAsString(value));
    }

}
